package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constants.MessageConstant;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(path = "/member")
public class MemberController {

    @Reference
    private MemberService memberService;

    @RequestMapping(path = "/add")
    public Result add(@RequestBody Member member){

        try{
                memberService.add(member);
            return new Result(true, MessageConstant.ADD_MEMBER_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_MEMBER_FAIL);
        }
    }

    @RequestMapping(path = "/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return memberService.findPage(queryPageBean);
    }

    @RequestMapping(path = "/findById")
    public Result findById(@RequestParam("id") Integer id){
     Member member = memberService.findById(id);
        if (member != null) {
            return new Result(true,MessageConstant.QUERY_MEMBER_SUCCESS,member);
        }
        return new Result(false,MessageConstant.QUERY_MEMBER_FAIL);
    }

    @RequestMapping(path = "/edit")
    public Result edit(@RequestBody Member member){
        try {
            memberService.edit(member);
            return new Result(true,MessageConstant.EDIT_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_MEMBER_FAIL);
        }
    }

    @RequestMapping(path = "/deleteById")
    public Result deleteById(@RequestParam("id") Integer id){
        try {
            memberService.deleteById(id);
            return new Result(true,MessageConstant.DELETE_MEMBER_SUCCESS);
        }catch (RuntimeException e){
            return new Result(false,e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.DELETE_MEMBER_FAIL);
        }
    }
}
